<template>
  <div>
    <Navbar appTitle="申请退料" />
    <div class="search-content wrap-apply" :style="{top: GLOBAL.currentEnvironment ? '0' : '',height: GLOBAL.currentEnvironment ? '100vh' : 'calc(100vh - 1.12rem)',paddingBottom: GLOBAL.currentEnvironment ? '1rem' : ''}">
      <van-cell-group style="margin-top: 0.1rem">
        <p class="label required FormTit"><span></span>工单编号</p>
        <!-- <van-field v-model="buildForm.orderCode" placeholder="请输入" /> -->
        <scanInput
          ref="scanInput"
          :key="index"
          :columns="columns"
          @changeScan="changeScan"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>生产物料</p>
        <van-field
          readonly
          v-model="goodsFullName"
          placeholder="请选择工单编号"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>基本单位</p>
        <van-field
          readonly
          v-model="buildForm.goodsBasicUnitText"
          placeholder="请选择工单编号"
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>退料人</p>
        <van-field
          is-link
          readonly
          name="picker"
          v-model="createdByName"
          @click="ddthrVisible = true"
          placeholder="请选择"
          :rules="[{ required: true, message: '请选择退料人' }]"
        >
        </van-field>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label FormTit"><span></span>退料时间</p>
        <van-field
          is-link
          readonly
          name="picker"
          v-model="buildForm.returnTime"
          @click="returnTimeModal = true"
          placeholder="请选择"
        >
          <template slot="right-icon" v-if="buildForm.returnTime">
            <img
              src="~@/assets/img/filedClear.png"
              alt=""
              @click.stop="clickClose"
              style="width: 0.16rem; height: 0.16rem"
            />
          </template>
        </van-field>
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <p class="label required FormTit"><span></span>退料原因</p>
        <van-field v-model="buildForm.reason" placeholder="请输入" />
        <div class="bottomLine"></div>
      </van-cell-group>

      <van-cell-group style="margin-top: 0.1rem">
        <div class="label otherText">
          <div style="display: inline-block">
            <img
              @click="changeItem(true)"
              v-if="checkboxList.length == 0"
              style="width: 0.2rem; height: 0.2rem; margin-top: -0.05rem"
              src="../../../assets/btna.png"
              alt=""
            />
            <img
              @click="changeItem(true)"
              v-if="
                checkboxList.length !== 0 &&
                checkboxList.length !== goodsList.length
              "
              style="width: 0.22rem; height: 0.22rem; margin-top: -0.05rem"
              src="../../../assets/btnb.png"
              alt=""
            />
            <!-- 勾选 -->
            <img
              @click="changeItem(false)"
              v-if="
                checkboxList.length !== 0 &&
                checkboxList.length === goodsList.length
              "
              style="width: 0.22rem; height: 0.22rem; margin-top: -0.05rem"
              src="../../../assets/btnc.png"
              alt=""
            />
          </div>
          <span class="goodsTitleOne">退还物料</span>
        </div>
        <div class="bottomLine"></div>

        <van-checkbox-group
          v-model="checkboxList"
          ref="checkboxGroup"
          direction="horizontal"
          @change="changeCheckValue"
        >
          <div class="checkF">
            <van-checkbox
              v-for="(item, index) in goodsList"
              :key="index"
              class="wrap"
              :name="item"
              shape="square"
              :label-disabled="true"
            >
              <p class="goodsTitle">
                {{ item.goodsCode }}-{{ item.goodsName }}
              </p>
              <p class="goodsCell">
                <span class="goodsLabel">物料规格：</span>{{ item.goodsSpec }}
              </p>
              <p class="goodsCell">
                <span class="goodsLabel">总领补量：</span
                >{{ item.totalReceivedRemedyNum }} {{ item.goodsBasicUnitText }}
              </p>
              <p class="goodsCell">
                <span class="goodsLabel">已退量：</span>{{ item.returnNum }}
                {{ item.goodsBasicUnitText }}
              </p>
              <p class="goodsCell">
                <span class="goodsLabel">在申退量：</span>{{ item.lockNum }}
                {{ item.goodsBasicUnitText }}
              </p>
              <van-cell-group>
                <van-field
                  width="100%"
                  v-model="item.num"
                  placeholder="请输入本次退料量"
                  @input="changeNum(item)"
                >
                  <template #right-icon>
                    {{ item.goodsBasicUnitText }}
                  </template>
                </van-field>
                <div class="bottomLine"></div>
              </van-cell-group>
            </van-checkbox>
          </div>
        </van-checkbox-group>
      </van-cell-group>

      <van-cell-group style="margin-top: 0.1rem">
        <p class="label otherText">其他</p>
        <div class="bottomLine"></div>
        <p class="label">备注</p>
        <van-field
          v-model="buildForm.remark"
          rows="2"
          autosize
          label=""
          type="textarea"
          maxlength="50"
          placeholder="请输入备注"
          show-word-limit
        />
        <div class="bottomLine"></div>
      </van-cell-group>
      <van-cell-group>
        <!-- <upload
          :key="index"
          iconType="fj"
          @fileChange="fileChange"
          :fileIds="attachment"
        /> -->
        <fileSelector
          iconType="fj"
          :title="'附件'"
          @fileChange="fileChange"
          :fileIds="attachment"
        ></fileSelector>
      </van-cell-group>
      <div style="margin-top: 0.1rem">
        <Examine
          type="0"
          ref="Examine"
          @submitProcess="submitProcess"
          id="MESS_RETURN_MATERIAL_APPLY"
          :key="index"
        />
      </div>
      
      <!--退料时间 -->
      <van-popup v-model="returnTimeModal" position="bottom">
        <van-datetime-picker
          v-model="nowTime"
          @confirm="confirmReturnTime"
          @cancel="cancelReturnTime"
          type="date"
          title="退料时间"
          :formatter="formatter"
        />
      </van-popup>
      <div class="search-bottoms">
        <span class="btnconfirm" @click="submitProcess">确定</span>
      </div>
    </div>
    <contact-pickers
      :key="index"
      :visible="ddthrVisible"
      @confirm="confirmDdtjr"
      @closePicker="closePicker"
      :max="1"
    >
    </contact-pickers>
    
  </div>
</template>
<script>
import { filter } from "lodash";

import Navbar from "@/components/navBar/navBar_right";
import scanInput from "@/components/scanCode/scanInput";
import ContactPickers from "@/components/choiceuse/ContactPickers";
import upload from "@/components/upload/upload";
import VanFieldSelectPicker from "@/components/ActionSheet/VanFieldSelectPicker";
import { processTaskCompletionStatics } from "@/api/mobile";
import moment from "moment";
import { clearNoNum, accAdd, accSub } from "@/utils/util";
import Examine from "@/components/examine";
import { APILX } from "@/api/requestLx";
import fileSelector from "@/components/fileSelector.vue";
export default {
  name: "returnMaterialForm", //退料单
  components: {
    ContactPickers,
    upload,
    VanFieldSelectPicker,
    Navbar,
    scanInput,
    Examine,
    fileSelector
  },

  data() {
    return {
      goodsFullName: "", //生产物料
      numIndex: 0,
      index: "",
      attachment: "", //附件
      goodsList: [],
      checkboxList: [], //列表选中的数据
      checkboxData: [], //列表数据
      orderList: [], //工单列表
      //补用时间
      returnTimeModal: false,
      nowTime: new Date(),
      buildForm: {
        orderId: "",
        returnTime: "",
        goodsName: "",
        goodsBasicUnitText: "",
        returnerId: "", //退料人
        remark: "",
        reason: "", //退料原因
      },
      createdByName: "", //操作人
      ddthrVisible: false,
      columns: [],
      timeSS: "",
    };
  },
  // 路由返回时先判断当前页是否存在弹窗，有就先关闭弹窗不返回，直到所有弹窗关闭再返回
  beforeRouteLeave(to, from, next) {
    let that = this;
    switch (true) {
      // that.showSearchTag是当前页的筛选弹窗，that.$refs.SearchTag.ddthrVisible是子组件筛选弹窗内的其他弹窗例如人员选择
      case that.ddthrVisible:
        that.ddthrVisible = false;
        next(false);
        break;
      case !that.ddthrVisible:
        next();
        break;
    }
  },
  computed: {},
  mounted() {},
  created() {
    this.getOrderList();
    this.getDetail();
  },
  methods: {
    clickClose() {
      this.buildForm.returnTime = "";
      this.timeSS = "";
    },
    getDetail() {
      console.log(this.$route.query.orderId, "this.$route.query.orderId");
      if (this.$route.query.orderId) {
        this.getMaterial(this.$route.query.orderId, "scan");
      }
    },
    //   input事件
    changeNum(item) {
      item.num = clearNoNum(item.num);
      if (item.num > item.canNum) {
        item.num = item.canNum;
      }
    },
    indexChange() {
      this.index += 1;
    },
    fileChange(ids) {
      this.attachment = ids;
      console.log("父组件" + ids); //你要保存的fileids
    },
    changeCheckValue(v) {
      console.log(v, "0..0.0.0.");
      this.checkboxData.push(v);
      if (v.length === this.columns.length) {
      } else {
      }
    },
    // 控制全选、清空
    changeItem(v) {
      console.log(v, "aaaitem");
      this.$refs.checkboxGroup.toggleAll(v);
    },
    getOrderList() {
      APILX.productOrderList({
        pageSize: "999",
        statusListStr: "notStarted,inProduction",
      }).then((res) => {
        if (res.code == 200) {
          this.orderList = res.result.records;
          console.log(this.orderList, "工单列表");
          //   筛选出orderList里面的id和orderCode到columns里面
          this.columns = this.orderList.map((item) => {
            return {
              key: item.orderCode,
              value: item.id,
            };
          });
          this.getDetail();
        }
      });
    },
    changeScan(v, opratorType) {
      console.log(v, "获取扫码组件数据");

      if (opratorType == "select") {
        //   let item = this.orderList.filter((item) => item.id === v.value);
        // console.log(item, "item");
        // if (item[0].status !== "inProduction") {
        //   this.$toast("生产工单无法退料");
        //   // this.index += 1;
        //   this.btnCancel();

        //   return;
        // }
        this.getMaterial(v.value, opratorType);
      }
      //value是下拉选择后值,code是扫码获得的值，根据qrcode判断是否隐藏当前页面只显示相机页
      if (opratorType == "scan") {
        if (v.code.EntityType != "workOrder") {
          this.$toast("请扫正确二维码");
          return;
        }
        // 开启了扫码
        this.getMaterial(v.code.id, opratorType);
      } else {
        //关闭了扫码
        // v.code为扫码的结果值
      }
    },
    // 获取物料
    getMaterial(v, opratorType) {
      if (!v) {
        return;
      }
      this.buildForm.orderId = v;
      let order = this.orderList.find((item) => item.id == v);
      if (order.status !== "inProduction") {
        this.$toast("生产工单无法退料");
        // this.index += 1;
        this.btnCancel();

        return;
      }
      this.buildForm.goodsBasicUnitText = order.goodsBasicUnitText;
      this.buildForm.goodsName = order.goodsName;
      this.goodsFullName = `${order.goodsCode}-${order.goodsName}`;
      if (opratorType == "scan") {
        let scanObj = {
          id: order.orderId,
          orderCode: order.orderCode,
        };
        this.$refs.scanInput.propValue(scanObj);
      }
      APILX.messReturnMaterialApplyQueryByOrderId({ orderId: v }).then(
        (res) => {
          if (res.result) {
            let goodsList = res.result;
            console.log(goodsList, "goodsList0.0.0.0.00.");
            if (goodsList.length == 0) {
              this.$toast("该工单无可退料量");
              this.btnCancel();
              return;
            }
            goodsList.forEach((item) => {
              let num = item.canNum;
              if (Number(num) < 0) {
                item.num = 0;
              } else {
                item.num = num;
              }
            });
            // for (let item of goodsList) {
            //   let num =
            //     Number(item.receivedNum) -
            //     Number(item.returnNum) -
            //     Number(item.lockNum);
            //   console.log(num, "num");
            //   if (Number(num) < 0) {
            //     item.num = 0;
            //     console.log(item.num, "进来小于0  tem.num");
            //     console.log(num, "进来小于0  num");
            //   } else {
            //     item.num = num;
            //   }
            // }
            // for (let i = 0; i++; i <= goodsList.length) {
            //   let num =
            //     Number(goodsList[i].receivedNum) -
            //     Number(goodsList[i].returnNum) -
            //     Number(goodsList[i].lockNum);
            //   console.log(num, "num");
            //   if (Number(num) < 0) {
            //     goodsList[i].num = 0;
            //     console.log(goodsList[i].num, "进来小于0  tem.num");
            //     console.log(num, "进来小于0  num");
            //   } else {
            //     goodsList[i].num = num;
            //   }
            // }
            this.goodsList = goodsList;
            console.log(this.goodsList, goodsList, "获取物料详情");
          }
        }
      );
      console.log(order, "orderList");
    },
    // 选人
    confirmDdtjr(val, selectedList, judge) {
      this.buildForm.returnerId = "";
      this.createdByName = "";
      if (judge) {
        this.ddthrVisible = false;
        return;
      }
      this.buildForm.returnerId = val ? val : ""; //人员id
      let arr = [];
      if (selectedList) {
        selectedList.forEach((item) => {
          arr.push(item.realname);
        });
      }
      this.createdByName = arr.join(",");
      this.ddthrVisible = false;
    },
    // 关闭选人组件
    closePicker() {
      this.ddthrVisible = false;
    },
    // 重置
    btnCancel() {
      //   this.$refs.topSearch.value = "";
      this.buildForm = {
        returnTime: null, //退料时间展示
        goodsName: null,
        goodsBasicUnitText: null,
        returnerId: null,
        remark: null,
        orderId: null,
      };
      this.nowTime = new Date(); //滑动了的时间重置
      this.timeSS = ""; //退料时间
      this.goodsList = []; //物料
      this.checkboxList = []; //选择的物料
      this.goodsFullName = ""; //物料全名称
      (this.attachment = null),
        (this.createdByName = null), //选人展示
        this.indexChange(); //扫码组件重置
    },
    // 获取流程数据
    submitProcess(e) {
      console.log(this.buildForm.orderId, "this.buildForm");

      if (!this.buildForm.orderId) {
        this.$toast("请选择工单编号");
        return;
      }
      if (!this.buildForm.returnerId) {
        this.$toast("请选择退料人");
        return;
      }
      if (!this.buildForm.reason) {
        this.$toast("请输入退料原因");
        return;
      }
      if (this.checkboxList == 0) {
        this.$toast("请选择物料");
        return;
      }
      //  如果 this.checkboxList里面的num为空 则return
      this.checkboxList.forEach((item) => {
        if (item.num == "") {
          this.numIndex++;
        }
      });
      if (this.numIndex > 0) {
        this.$toast("请输入退料数量");
        this.numIndex = 0;
        return;
      }
      if (this.checkboxList == 0) {
        this.$toast("请选择物料");
        return;
      }
      console.log(e, "eee");
      if (e.nodeDtos) {
        console.log(e);
        this.btnConfirm(e);
      } else {
        this.$refs.Examine.confirm();
      }
    },
    // 表单提交
    btnConfirm(processDataVo) {
      let params = {
        ...this.buildForm,
        messPlanMaterialApplyDtoList: this.checkboxList,
        attachment: this.attachment,
        processDataVo: processDataVo,
      };
      params.returnTime = this.timeSS;
      APILX.returnMaterialAdd(params).then((res) => {
        if (res.code == 200) {
          this.$toast(res.message);
          //   返回上一级
          this.$router.go(-1);
        } else {
          this.$toast(res.message);
        }
      });
      console.log(params, "sureObjsureObjsureObj");
    },

    // 选择时间
    confirmReturnTime(date) {
      this.buildForm.returnTime = moment(date).format("YYYY-MM-DD");
      this.timeSS = moment(date).format("YYYY-MM-DD HH:mm:ss");
      this.returnTimeModal = false;
    },
    // 取消选择时间
    cancelReturnTime() {
      this.returnTimeModal = false;
    },
    formatter(type, val) {
      if (type === "year") {
        return val + "年";
      }
      if (type === "month") {
        return val + "月";
      }
      if (type === "day") {
        return val + "日";
      }
      if (type === "hour") {
        return val + "时";
      }
      if (type === "minute") {
        return val + "分";
      }
      return val;
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/theme.scss";
@import "@/views/workManagement/materialRequisition/materialForm.scss";
.search-bottoms {
  width: 100%;
  height: 0.5rem;
  background: #ffffff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: fixed;
  bottom: 0px;
  padding: 0rem 0.11rem;
  box-sizing: border-box;
  font-size: 0.16rem;
  font-weight: 500;
  z-index: 9;
  .btnconfirm {
    flex: 1;
    background: #1890ff;
    box-sizing: border-box;
    height: 0.39rem;
    display: flex;
    justify-content: center;
    align-items: center;
    border-radius: 0.03rem;
    color: #ffffff;
  }
}
</style>
